package netty;

import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;

/**
 *
 */
public class NettyClientHandler extends ChannelInboundHandlerAdapter {
    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        System.out.println("read msg from server...");
        ByteBuf buf = (ByteBuf) msg;
        byte[] date = new byte[buf.readableBytes()];
        buf.readBytes(date);
        System.out.println("server msg: " + new String(date));
        buf.release();

        Thread.sleep(10000);
        System.out.println("send msg to server...");
        String response = "hello server";
        ByteBuf buf1 = ctx.alloc().buffer();
        buf1.writeBytes(response.getBytes());
        ctx.write(buf1);
        ctx.flush();
    }

    /**
     * channel生命周期回调函数，channel准备好后回调此函数，不能少，否则bs交互无法发起
     * @param ctx
     * @throws Exception
     */
    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        System.out.println("firstly send msg to server...");
        String msg = "hello server!";
        ByteBuf encode = ctx.alloc().buffer(4 * msg.length());
        encode.writeBytes(msg.getBytes());
        ctx.write(encode);
        ctx.flush();
    }


}
